package yunwo.cn.yzstation.utils;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.media.ExifInterface;
import android.os.Build;
import android.view.WindowManager;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class DrawableUtils {

	private static final String TAG = "DrawableUtils";

	/**
	 * 创建一个图片
	 * 
	 * @param contentColor
	 *            内部填充颜色
	 * @param strokeColor
	 *            描边颜色
	 * @param radius
	 *            圆角
	 */
	public static GradientDrawable createDrawable(int contentColor,
												  int strokeColor, int radius) {
		GradientDrawable drawable = new GradientDrawable(); // 生成Shape
		drawable.setGradientType(GradientDrawable.RECTANGLE); // 设置矩形
		drawable.setColor(contentColor);// 内容区域的颜色
		drawable.setStroke(1, strokeColor); // 四周描边,描边后四角真正为圆角，不会出现黑色阴影。如果父窗体是可以滑动的，需要把父View设置setScrollCache(false)
		drawable.setCornerRadius(radius); // 设置四角都为圆角
		return drawable;
	}

	/**
	 * 创建一个图片选择器
	 * 
	 * @param normalState
	 *            普通状态的图片
	 * @param pressedState
	 *            按压状态的图片
	 */
	public static StateListDrawable createSelector(Drawable normalState,
												   Drawable pressedState) {
		StateListDrawable bg = new StateListDrawable();
		bg.addState(new int[] { android.R.attr.state_pressed,
				android.R.attr.state_enabled }, pressedState);
		bg.addState(new int[] { android.R.attr.state_enabled }, normalState);
		bg.addState(new int[] {}, normalState);
		return bg;
	}

	/** 获取图片的大小 */
	@SuppressLint("NewApi")
	public static int getDrawableSize(Drawable drawable) {
		if (drawable == null) {
			return 0;
		}
		Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
			return bitmap.getByteCount();
		} else {
			return bitmap.getRowBytes() * bitmap.getHeight();
		}
	}

	/**
	 * 把图片变成圆角
	 * 
	 * @param bitmap
	 *            需要修改的图片
	 * @param pixels
	 *            圆角的弧度
	 * @return 圆角图片
	 */
	public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {

		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		final float roundPx = pixels;

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);

		return output;
	}

	/**
	 * 转换图片成圆形
	 * 
	 * @param bitmap
	 *            传入Bitmap对象
	 * @return
	 */
	public static Bitmap makeRoundCorner(Bitmap bitmap) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		float roundPx;
		float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
		if (width <= height) {
			roundPx = width / 2;
			top = 0;
			bottom = width;
			left = 0;
			right = width;
			height = width;
			dst_left = 0;
			dst_top = 0;
			dst_right = width;
			dst_bottom = width;
		} else {
			roundPx = height / 2;
			float clip = (width - height) / 2;
			left = clip;
			right = width - clip;
			top = 0;
			bottom = height;
			width = height;
			dst_left = 0;
			dst_top = 0;
			dst_right = height;
			dst_bottom = height;
		}

		Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect src = new Rect((int) left, (int) top, (int) right,
				(int) bottom);
		final Rect dst = new Rect((int) dst_left, (int) dst_top,
				(int) dst_right, (int) dst_bottom);
		final RectF rectF = new RectF(dst);

		paint.setAntiAlias(true);

		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, src, dst, paint);
		return output;
	}

	/**
	 * 根据图片的路径压缩图片
	 * 
	 * @param picturePath
	 * @return
	 */
	public static Bitmap compressPic(String picturePath,
									 WindowManager windowManager) {
		Options options = new Options();
		options.inDither = false;// 设置为false，将不考虑图片的抖动值，这会减少图片的内存占用
		options.inPurgeable = true;// 设置为ture，表示允许系统在内存不足时，删除bitmap的数组。
		options.inInputShareable = true;
		return decodeSampledBitmapFromResource(picturePath, 100, 100, options);
	}

	/**
	 * 根据图片的路径压缩图片
	 * 
	 * @param picturePath
	 * @return
	 */
	public static Bitmap compressPic(String picturePath, int reqWidth,
									 int reqHeight) {
		Options options = new Options();
		options.inDither = false;// 设置为false，将不考虑图片的抖动值，这会减少图片的内存占用
		options.inPurgeable = true;// 设置为ture，表示允许系统在内存不足时，删除bitmap的数组。
		options.inInputShareable = true;
		return decodeSampledBitmapFromResource(picturePath, reqWidth,
				reqHeight, options);
	}

	// 存储进SD卡
	public static File saveFile(String filePath) throws Exception {
		// File dirFile = new File(fileName);
		// // 检测图片是否存在
		// if (dirFile.exists()) {
		// dirFile.delete(); // 删除原图片
		// }
		File dirFile = new File(filePath);
		String fileNname = dirFile.getName();
//		LogUtil.d(TAG, "fileNname:" + fileNname);
		File myCaptureFile = new File(FileUtil.getIconDir() + fileNname);

		Bitmap bitmap = decodeSampledBitmapFromResource(filePath, 480, 800,new Options());
		if(bitmap!=null) {
			Options options = new Options();
			options.inDither = false;// 设置为false，将不考虑图片的抖动值，这会减少图片的内存占用
			options.inPurgeable = true;// 设置为ture，表示允许系统在内存不足时，删除bitmap的数组。
			options.inInputShareable = true;

			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(myCaptureFile));
			// 100表示不进行压缩，70表示压缩率为30% >100K
			bitmap.compress(Bitmap.CompressFormat.JPEG, 30, bos);
			bos.flush();
			bos.close();
		}
		return myCaptureFile;
	}

	public static File saveFile(Bitmap bitmap, String fileName, int quality)
			throws Exception {
		Options options = new Options();
		options.inDither = false;// 设置为false，将不考虑图片的抖动值，这会减少图片的内存占用
		options.inPurgeable = true;// 设置为ture，表示允许系统在内存不足时，删除bitmap的数组。
		options.inInputShareable = true;
//		LogUtil.d(TAG, "fileNname:" + fileName);
		File myCaptureFile = new File(FileUtil.getIconDir() + fileName + ".jpg");
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(myCaptureFile));
		// 100表示不进行压缩，70表示压缩率为30% >100K
		bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos);

		//CutPicActivity.bitmap = null;
		bos.flush();
		bos.close();
		return myCaptureFile;
	}

	public static File saveCutPicFile(Bitmap bitmap, String filePath)
			throws Exception {
		Options options = new Options();
		options.inDither = false;// 设置为false，将不考虑图片的抖动值，这会减少图片的内存占用
		options.inPurgeable = true;// 设置为ture，表示允许系统在内存不足时，删除bitmap的数组。
		options.inInputShareable = true;
//		LogUtil.d(TAG, "filePath:" + filePath);
		File myCaptureFile = new File(filePath);
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(myCaptureFile));
		// 100表示不进行压缩，70表示压缩率为30% >100K
		bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
		bos.flush();
		bos.close();
		return myCaptureFile;
	}

	/**
	 * 根据图片的路径压缩图片（默认压缩100*100）
	 * 
	 * @param picturePath
	 * @return
	 */
	public static Bitmap compressPic(String picturePath) {
		Options options = new Options();
		options.inDither = false;// 设置为false，将不考虑图片的抖动值，这会减少图片的内存占用
		options.inPurgeable = true;// 设置为ture，表示允许系统在内存不足时，删除bitmap的数组。
		options.inInputShareable = true;
		return decodeSampledBitmapFromResource(picturePath, 100, 100, options);
	}

	// 计算原始宽高要缩小的比率
	public static int calculateInSampleSize(Options options,
			int reqWidth, int reqHeight) {
		// Raw height and width of image.①得到图片的原始宽和高
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;// ②设置比率

		if (height > reqHeight || width > reqWidth) {

			// ③分别计算宽和高的压缩比率 Calculate ratios of height and width to requested
			// height and width
			final int heightRatio = Math.round((float) height
					/ (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);

			// ④取两个比率的最小值，这样可以保证最终图片的宽和高的尺寸大于或者等于所需图片的宽和高。
			// Choose the smallest ratio as inSampleSize value, this will
			// guarantee
			// a final image with both dimensions larger than or equal to the
			// requested height and width.
			inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
		}

		return inSampleSize;
	}

	/**
	 * 解码：根据需求的宽和高来按比率解码原始图片的宽和高
	 */
	public static Bitmap decodeSampledBitmapFromResource(int resId,
														 int reqWidth, int reqHeight, Options options) {
		// First decode with inJustDecodeBounds=true to check dimensions
		// ①首先设置inJustDecodeBounds = true,为的只是检查原始图片的宽和高。
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeResource(UIUtils.getResources(), resId, options);

		// ②计算比率 Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, reqWidth,
				reqHeight);

		// ③设置inJustDecodeBounds = false，让解码的结果不返回为null。 Decode bitmap with
		// inSampleSize set
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeResource(UIUtils.getResources(), resId,
				options);
	}

	/**
	 * 解码：根据需求的宽和高来按比率解码原始图片的宽和高
	 */
	public static Bitmap decodeSampledBitmapFromResource(FileDescriptor fd,
														 Rect outPadding, int reqWidth, int reqHeight,
														 Options options) {
		// First decode with inJustDecodeBounds=true to check dimensions
		// ①首先设置inJustDecodeBounds = true,为的只是检查原始图片的宽和高。
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFileDescriptor(fd, outPadding, options);

		// ②计算比率 Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, reqWidth,
				reqHeight);

		// ③设置inJustDecodeBounds = false，让解码的结果不返回为null。 Decode bitmap with
		// inSampleSize set
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeFileDescriptor(fd, outPadding, options);
	}

	/**
	 * 解码：根据需求的宽和高来按比率解码原始图片的宽和高
	 */
	public static Bitmap decodeSampledBitmapFromResource(String pathName,
														 int reqWidth, int reqHeight, Options options) {

		int readPictureDegree = readPictureDegree(pathName);
//		LogUtil.d(TAG, "readPictureDegree:" + readPictureDegree);
		// First decode with inJustDecodeBounds=true to check dimensions
		// ①首先设置inJustDecodeBounds = true,为的只是检查原始图片的宽和高。
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(pathName, options);

		// ②计算比率 Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, reqWidth,
				reqHeight);

		// ③设置inJustDecodeBounds = false，让解码的结果不返回为null。 Decode bitmap with
		// inSampleSize set
		options.inJustDecodeBounds = false;

		File file = new File(pathName);
		FileInputStream fs = null;
		Bitmap decodeFileDescriptor = null;
		Bitmap rotateBitmap = null;
		try {
			fs = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		try {
			if (fs != null) {
				// decodeFileDescriptor = BitmapFactory.decodeFile(pathName,
				// options);
				decodeFileDescriptor = BitmapFactory.decodeFileDescriptor(
						fs.getFD(), null, options);
				rotateBitmap = rotateBitmap(decodeFileDescriptor,
						readPictureDegree);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fs != null) {
				try {
					fs.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return rotateBitmap;
	}
	
	public static Bitmap pathToBitmap(String path){
		try {
			URL url = new URL(path);
			   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			   int code = conn.getResponseCode();
			   if(conn.getResponseCode()==200){
				   conn.connect();
				   InputStream is = conn.getInputStream();
				   ByteArrayOutputStream baos = new ByteArrayOutputStream();
				   byte[] buffer = new byte[10*1024*1024];
				   int len;
				   while ((len = is.read(buffer)) != -1) {
					   baos.write(buffer, 0, len);
				   }
				   byte[] result = baos.toByteArray();
				   return BitmapFactory.decodeByteArray(result, 0, result.length);
			   }
			   return null;
		}
		catch (Exception e) {
			// TODO: handle exception
			return null;
		}
	}
	
	/**
	 * 根据图片的url路径获得Bitmap对象
	 * @param url
	 * @return
	 */
	public static Bitmap returnBitmap(String url) {
	    URL fileUrl = null;
	    Bitmap bitmap = null;
	 
	    try {
	        fileUrl = new URL(url);
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	 
	    try {
	        HttpURLConnection conn = (HttpURLConnection) fileUrl
	                .openConnection();
	        conn.setDoInput(true);
	        conn.connect();
	        InputStream is = conn.getInputStream();
	        bitmap = BitmapFactory.decodeStream(is);
	        is.close();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	    return bitmap;
	 
	}

	/**
	 * 读取图片属性：旋转的角度
	 * 
	 * @param path
	 *            图片绝对路径
	 * @return degree旋转的角度
	 */
	public static int readPictureDegree(String path) {
		int degree = 0;
		try {
			ExifInterface exifInterface = new ExifInterface(path);
			int orientation = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
			return degree;
		}
		return degree;
	}

	/**
	 * 旋转图片，使图片保持正确的方向。
	 * 
	 * @param bitmap
	 *            原始图片
	 * @param degrees
	 *            原始图片的角度
	 * @return Bitmap 旋转后的图片
	 */
	public static Bitmap rotateBitmap(Bitmap bitmap, int degrees) {
		if (degrees == 0 || null == bitmap) {
			return bitmap;
		}
		Matrix matrix = new Matrix();
		matrix.setRotate(degrees, bitmap.getWidth() / 2, bitmap.getHeight() / 2);
		Bitmap bmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
				bitmap.getHeight(), matrix, true);
		if (null != bitmap) {
			bitmap.recycle();
		}
		return bmp;
	}

	/**
	 * 将inputStream 转换为bitmap
	 */
	

	public static Bitmap getImageView(InputStream inputStream) {
		Bitmap bitmap = null;
		  ByteArrayOutputStream out = null;
		  BufferedOutputStream outputStream = null;
		try {
			out = new ByteArrayOutputStream();
			outputStream = new BufferedOutputStream(out);
			byte[] b = new byte[1024];
			int read;
			if (inputStream != null) {
				try {
					while ((read = inputStream.read(b)) != -1) {
						outputStream.write(b, 0, read);
						outputStream.flush();
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				byte[] data = out.toByteArray();
				bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
				data = null;
				return bitmap;
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}
}
